package custom.security.browser.authentication;

import com.fasterxml.jackson.databind.ObjectMapper;
import custom.security.core.properties.SecurityProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 *  用户请求成功后处理器
 * Created by wgt on 2017/10/14.
 */
@Slf4j
@Component
public class CustomAuthticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {


    @Autowired
    private SecurityProperties securityProperties;

    @Autowired
    private ObjectMapper objectMapper;

    /**
     * 用户请求成功做出的处理
     * @param httpServletRequest
     * @param httpServletResponse
     * @param authentication    验证后的用户信息
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest,
                                        HttpServletResponse httpServletResponse,
                                        Authentication authentication) throws IOException, ServletException {
        log.info("user login successfully by username:{}",authentication.getName());

        /**
         * 如果在配置中指定了请求的响应格式为json，则将用户验证的信息由json格式返回
         * 未配置则根据请求原本的响应格式进行响应
         */
        if (AuthenticationConstant.RESPONSE_TYPE_JSON.equalsIgnoreCase(securityProperties.getBrowser().getResponseType())) {
            httpServletResponse.setContentType(AuthenticationConstant.CONTENT_TYPE_APPLICATION_JSON);
            httpServletResponse.getWriter().write(objectMapper.writeValueAsString(authentication));
            return;
        }
        super.onAuthenticationSuccess(httpServletRequest,httpServletResponse,authentication);
    }

}
